import requests
import os

url = "https://kkzycdn.com:65/20221212/EYw5LXjM/2000kb/hls/41RKcMYj.ts"
file_name = '樱花视频.mp4'

try:
    response = requests.get(url, stream=True)
    response.raise_for_status()  # 检查请求是否成功

    # 获取文件大小
    file_size = int(response.headers.get('Content-Length', 0))

    # 初始化已下载的字节数
    downloaded = 0

    # 以二进制写入模式打开文件
    with open(file_name, 'ab') as f:
        # 遍历响应内容的每个数据块
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
                downloaded += len(chunk)
                # 计算下载进度
                progress = (downloaded / file_size) * 100 if file_size > 0 else 0
                print(f"\r下载进度: {progress:.2f}%", end='', flush=True)

    print("\n文件下载成功！")
except requests.RequestException as e:
    print(f"下载过程中发生网络错误: {e}")
except OSError as e:
    print(f"文件写入时发生错误: {e}")
except Exception as e:
    print(f"发生未知错误: {e}")